import { Request, Response } from 'express';
import IResponse from '@/utils/IResponse';

/** 延时 */
const waitTime = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

/** 随机生成boolean类型 */
const bool = (max: number, min: number) => {
  let range = max - min;
  let rand = Math.random();
  return min + Math.round(rand * range) !== min;
};

const generateLoginCaptcha = () => {
  let codes = [
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z',
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
  ];

  let captcha = [];
  for (let i = 0; i < 4; i++) {
    let index = Math.floor(Math.random() * (35 - 0));
    captcha.push(codes[index]);
  }
  return captcha.join('');
};

export default {
  '/api/verify/login_captcha': async (req: Request, res: Response) => {
    await waitTime(1000);

    let result = bool(10, 0);

    let response_200: IResponse = {
      success: true,
      data: generateLoginCaptcha(),
    };
    let response_404: IResponse = {
      success: true,
      errorCode: '404',
      errorMessage: '获取验证码失败，请重试',
    };

    if (result) {
      res.status(200).json(response_200);
    } else {
      res.status(404).json(response_404);
    }
  },
};
